package com.ivan.serverice;

import com.ivan.config.JwtConfig;
import com.ivan.entity.User;
import com.ivan.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author 11900
 * @version V1.0
 * @Title: ${FILE_NAME}
 * @Package serverice
 * @Description: TODO
 * @date 2020/4/27 11:23
 */
@Service
public class JwtService implements IJwtService {

    //服务器的key /** 秘钥 */
//    public static final String JWT_KEY = "jwt_token";
    private Logger logger = LoggerFactory.getLogger(JwtService.class);
    @Autowired
    private RedisUtil redisUtil;
    /**
     * jwt token超时时间，单位ms
     */


    @Autowired
    private JwtConfig jwtConfig;


 /*   public void setExpireTime(int expireTime) {
        this.expireTime = expireTime * 60 * 1000;
    }*/

    /**
     * Description:登录获取token
     *
     * @param user user
     * @return java.lang.String
     * @author ivan
     * @date 2019/3/4 18:45
     */
    @Override
    public ResultUtil login(User user) {
        //进行登录校验
        try {
            if (user.getName().equalsIgnoreCase(user.getPassword())) {
                    String token = JwtUtils.createJWT(UUID.randomUUID().toString(), jwtConfig.getIss(), user.getName(), jwtConfig.getExpiretime()*60*1000);
                redisUtil.set(token,user,jwtConfig.getExpiretime()*60*1000);
                    return ResultUtil.ok(null,token);
            } else {
                return ResultUtil.build(CommonCode.USERNOTLOGIN);
            }
        } catch (Exception e) {
            return ResultUtil.build(CommonCode.USERNOTLOGIN);
        }
    }




    /**
     * Description:检查jwt有效性
     *
     * @return Boolean
     * @author ivan
     * @date 2019/3/4 18:47
     */
    @Override
    public ResultUtil checkJwt(String token) {
        CheckResult checkResult = JwtUtils.validateJWT(token);
        if (checkResult.isSuccess()&&redisUtil.hasKey(token)){
            return ResultUtil.ok(null);
        }
        return ResultUtil.build(CommonCode.USERNOTLOGIN);
    }

    @Override
    public ResultUtil refreshJwt(String token) {
        CheckResult checkResult = JwtUtils.validateJWT(token);
        if (checkResult.isSuccess()&&redisUtil.hasKey(token)){
            String newToken = JwtUtils.createJWT(checkResult.getClaims().getId(),checkResult.getClaims().getIssuer(),checkResult.getClaims().getSubject(),jwtConfig.getExpiretime()*60*1000);
            redisUtil.set(newToken,redisUtil.get(token),jwtConfig.getExpiretime()*60*1000);
            redisUtil.del(token);
            return ResultUtil.ok(checkResult.getClaims().getSubject(),newToken);
        }
        return ResultUtil.build(CommonCode.USERNOTLOGIN);
    }

    /**
     * Description: 使该jwt失效
     *
     * @author ivan
     * @date 2019/3/4 19:58
     */
    @Override
    public void inValid(String token) {

        redisUtil.del(token);
    }
}
